package com.base.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class ParamUtil {

    /**
     * 参数拼接
     */
    public static String getParam(Map<String, Object> paramsMap, String sign){
        // 返回拼接参数
        String param = "";

        try {List<String> params = new ArrayList<>();
            for (String key : paramsMap.keySet()) {
                String values = key + "=" + paramsMap.get(key);
                params.add(values);
            }
            for (int i = 0; i < params.size(); i++){
                if (i == 0){
                    param += params.get(i);
                }else {
                    param += "&" + params.get(i);
                }
            }
            // 参数不为空 拼接sign
            if (param != null && !param.equals("") && sign != null && !sign.equals("")){
                param += "&sign=" + sign;
            }
        }catch (Exception e){
            System.out.println("参数拼接失败");
        }

        return param;
    }

    public static String getSign(Map<String, Object> paramsMap, String appSecret){
        // 返回MD5签名
        String sign = "";

        try {
            List<String> params = new ArrayList<>();
            for (String key : paramsMap.keySet()) {
                String values = key + paramsMap.get(key);
                params.add(values);
            }
            if (params != null && params.size() > 0){
                //String.CASE_INSENSITIVE_ORDER A在 a 前面
                Collections.sort(params);
                // 获取拼接参数
                String param = "";
                for (int i = 0; i < params.size(); i++){
                    param += params.get(i);
                }
                // 参数不为空 拼接key
                if (param != null && !param.equals("")){
                    param = appSecret + param + appSecret;
                }
                System.out.println(param);
                sign = Md5Encrypt.encrypt32(param);
            }
        }catch (Exception e){
            System.out.println("签名生成失败");
        }

        return sign;
    }
}
